<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-width="100px"
      label-suffix=":"
    >

      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.color">
        <el-button v-loading="loading" type="success" @click="submitForm">
          保存
        </el-button>
      </sticky>

      <div class="app-container" style="padding: 10px 20px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="旧密码" prop="password_old">
              <el-input v-model.trim="postForm.password_old" type="password" />
            </el-form-item>
            <el-form-item label="新密码" prop="password">
              <el-input v-model.trim="postForm.password" type="password" />
            </el-form-item>
            <el-form-item label="重复密码" prop="password2">
              <el-input v-model.trim="postForm.password2" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>
  </div>
</template>

<script>
import api from '@/api'
import Sticky from '@/components/Sticky'
export default {
  name: 'Password',
  components: {
    Sticky
  },
  data() {
    const passwordValidate = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error('密码错误'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能小于6位'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      postForm: {
        color: 'draft'
      },
      rules: {
        password_old: [{ validator: passwordValidate, trigger: 'blur' }],
        password: [{ validator: passwordValidate, trigger: 'blur' }],
        password2: [{ validator: passwordValidate, trigger: 'blur' }]
      }
    }
  },
  created() {
  },
  methods: {
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          api.admin.password({
            ...this.postForm
          }).then(response => {
            this.loading = false
            this.$notify({
              title: '成功',
              message: response.message || '操作成功',
              type: 'success',
              duration: 2000
            })
            this.$store.dispatch('user/logout').then(() => {
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            })
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.detail-container {
  //
}
</style>
